package com.haohuo.sort;

import java.util.Arrays;

/**
 * 选择排序
 * note：
 * <p>
 * author: Caozhitong
 **/
public class SelectSort {

    public static void main(String[] args) {

        int[] elements = new int[]{1211, 212, 31, 422, 5222, 216, 712, 72, 733, 232, 453, 243, 233, 232};
        sort1(elements);
        Arrays.stream(elements).forEach(element -> System.out.print(element + ","));
    }

    public static void sort(int[] elements) {
        int index = 0;
        int minPos;
        while (index < elements.length - 1) {
            minPos = index;
            for (int i = index + 1; i < elements.length; i++) {
                if (elements[i] > elements[minPos]) {
                    minPos = i;
                }
            }
            int temp = elements[minPos];
            elements[minPos] = elements[index];
            elements[index] = temp;
            index++;
        }
    }


    public static void sort1(int[] elements) {
        int index = 0;
        int minPos;
        int maxPos;
        while (index < elements.length / 2) {
            minPos = index;
            maxPos = elements.length - 1 - index;

            for (int i = index; i < elements.length - index; i++) {
                if (i != index) {
                    if (elements[i] < elements[minPos]) {
                        minPos = i;
                    }
                }
                if (i != elements.length - 1 - index) {
                    if (elements[i] > elements[maxPos]) {
                        maxPos = i;
                    }
                }
            }

            if (maxPos == index && minPos == elements.length - 1 - index) {
                swap(elements, minPos, maxPos);
            } else {
                swap(elements, minPos, index);
                swap(elements, maxPos, elements.length - 1 - index);
            }
            index++;
        }
    }

    /**
     * 数组元素交换
     *
     * @param elements
     * @param i
     * @param j
     */
    private static void swap(int[] elements, int i, int j) {
        if (i != j) {
            int temp = elements[i];
            elements[i] = elements[j];
            elements[j] = temp;
        }
    }
}
